<template>
    <div id="Teach">
        <div class="jx-content">
            <div class="topcoumt">
                    <div class="search-box fl">
                        <el-form :inline="true"  :model="Form" class="fl">
                            <el-form-item label="教师信息 :" style="width:320px;">
                                <el-input v-model="Form.name" placeholder="请输入工号或者姓名" maxlength="20"></el-input>
                            </el-form-item>
                        </el-form>
                        <button class="button-style" @click="searchFn" >搜 索</button>
                    </div>
                    <div class="fr btn-box">
                        <button class="button-style" @click="addFn">添 加</button>
                        <button class="button-style" @click="deleteFn">批量删除</button>
                        <button class="button-style" @click="listProp" >批量导入</button>
                        <a class="button-style"  href="/tes/user/model/download/teacher" >模板下载</a>
                    </div>
            </div>
            <div class="table">
               <el-table :data="tableData" style="width: 100%"  @selection-change="handleSelectionChange">
                    <el-table-column  type="selection" width='100'></el-table-column>
                    <el-table-column prop="name" label="教师名称"></el-table-column>
                    <el-table-column prop="userNumber" label="工号" ></el-table-column>
                    <el-table-column prop="sexName" label="性别"> </el-table-column>
                    <el-table-column prop="telephoneNumber" label="手机号"></el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                    <el-table-column  label="操作">
                         <template slot-scope="scope">
                            <el-button type="text" size="small"  @click="repeatFn(scope.row.id,scope.row.name,scope.row.userNumber,scope.row.telephoneNumber,scope.row.email,scope.row.sexName)">修改</el-button>
                            <el-button type="text" size="small"  @click="repeatCode(scope.row.id)">初始密码</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
             <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="totalCount"
             ></el-pagination>
               <el-dialog :close-on-click-modal="false"  title="添加教师" :label-position="labelPosition" :visible.sync="dialogVisible" width="430px" @close="closeDialog">
                    <el-form ref="formlist" :inline="true"  :rules="rules" :model="formlist" >
                        <el-form-item label="姓  名 :" prop="name">
                            <el-input v-model="formlist.name" placeholder="请输入姓名" maxlength="10"></el-input>
                        </el-form-item>
                        <el-form-item label="工  号 :" prop="number">
                            <el-input v-model="formlist.number" placeholder="请输入工号"  maxlength="20"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号 :" prop="telephone" >
                            <el-input v-model="formlist.telephone" placeholder="请输入手机号" maxlength="11"></el-input>
                        </el-form-item>
                        <el-form-item label="邮  箱 :"  prop="email">
                            <el-input v-model="formlist.email" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="性  别 :"  prop="gender" >
                            <el-radio-group v-model="formlist.gender">
                                <el-radio label="男"></el-radio>
                                <el-radio label="女"></el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="密 码 :" prop="code">
                            <el-input v-model="formlist.code" maxlength="14" type="password" placeholder="请输入密码"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码 :" prop="codepass">
                            <el-input   v-model="formlist.codepass"  maxlength="14"  type="password" placeholder="请输入确认密码"></el-input>
                        </el-form-item>
                    </el-form>
                <div class="btn-center" style="text-align: center;">
                    <button class="button-style" @click="submitFn('formlist')"  >保 存</button>
                </div>
             </el-dialog>
            <el-dialog :close-on-click-modal="false"  title="修改教师" :label-position="labelPosition" :visible.sync="dialog" width="430px" >
                <el-form ref="formRepeat" :inline="true"  :rules="rules3" :model="formRepeat" >
                    <el-form-item label="姓  名 :" prop="name">
                        <el-input v-model="formRepeat.name" placeholder="请输入姓名" maxlength="10"></el-input>
                    </el-form-item>
                    <el-form-item label="工  号 :" prop="number">
                        <el-input v-model="formRepeat.number" placeholder="请输入工号"  maxlength="20" :disabled="true"></el-input>
                    </el-form-item>
                     <el-form-item label="手机号 :"  >
                        <el-input v-model="formRepeat.telephone" placeholder="请输入手机号" maxlength="11"></el-input>
                    </el-form-item>
                    <el-form-item label="邮  箱 :" >
                        <el-input v-model="formRepeat.email" placeholder="请输入邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="性  别 :" >
                        <el-radio-group v-model="formRepeat.gender">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <div class="btn-center" style="text-align: center;">
                    <button class="button-style" @click="submit('formRepeat')" >保 存</button>
                </div>
             </el-dialog>
             <el-dialog :close-on-click-modal="false"  title="导入教师" :visible.sync="dialogFormVisibles" width="500px" @close="closeTeacherDialog" >
               <el-form :model="form2" :rules="rules2" ref="form2">
                    <el-form-item  class="version-file">
                        <el-button class="button-style">上传文件<input id="version-files" type="file"  @change="getFile"></el-button>
                        <p v-if="form2.versionFile.length>0" style="margin:10px;">已选: {{form2.versionFile}}</p>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button  class="button-style" @click="saveForm('form2')">确认</el-button>
                </div>
            </el-dialog>
            <el-dialog :close-on-click-modal="false"  title="提示" :visible.sync="dialogTips" width="400px">
                <div class="dialogTips">
                    <p>
                        <i class="iconfont icon-jingshi "></i> 是否保留教师自定义课程
                    </p>
                    <el-radio-group v-model="flagExict" class="flagExict">
                        <el-radio :label="1">保留</el-radio>
                        <el-radio :label="2">不保留</el-radio>
                    </el-radio-group>
                        <div slot="footer" class="dialog-footer" style="margin-top:20px">
                        <el-button class="button-style" @click="dialogTipSave">确 定</el-button>
                    </div>
                </div>
            </el-dialog> 
        </div>
    </div>
</template>

<script>
    import $ from "jquery";
    export default {
        data () {
            //邮箱
            var validateEmail = (rule, value, callback) => {
                    if (value === '') {
                    callback(new Error('请正确填写邮箱'));
                    } else {
                    if (value !== '') {
                        var reg=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                        if(!reg.test(value)){
                        callback(new Error('请输入有效的邮箱'));
                        }
                    }
                    callback();
                    }
            }
            //手机号验证
            var validPhone = (rule, value,callback)=>{
                if (!value){
                    callback(new Error('请输入电话号码'))
                }else {
                    if (value !== '') {
                        var reg=/^[1][3,4,5,7,8][0-9]{9}$/;
                        if(!reg.test(value)){
                        callback(new Error('请输入正确的11位手机号码'));
                        }
                    }
                    callback();
                    }
            }
            // 密码验证
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                } else if(value !== ''){
                    var reg=/^[a-zA-Z0-9]{6,14}$/;
                    if(!reg.test(value)){
                        callback(new Error('请输入6-14位数字或中英文字符'))
                    }
                     if (this.formlist.codepass !== '') {
                        this.$refs.formlist.validateField('codepass')
                    }
                }
                callback()
            }
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'))
                } else if (value !== ''){
                    var reg=/^[a-zA-Z0-9]{6,14}$/;
                    if(!reg.test(value)){
                        callback(new Error('请输入6-14位数字或中英文字符'))
                    }
                    if (value !== this.formlist.code) {
					    callback(new Error('两次输入密码不一致!'))
                    }
                }
                callback()
            }
            return {
                Form:{
                    name:'',
                },
                role:'',
                id:'',
                labelPosition: 'right',
                dialog:false,
                dialogVisible:false,
                dialogFormVisibles:false,
                currentPage: 1,
                pagesize: 10,
                totalCount: 1000,
                tableData: [],
                multipleSelection:[],
                formlist:{
                     number:'',
                     name:'',
                     gender: '男',
                     codepass:'',
                     code:'',
                     telephone:'',
                     email:'',
                },
                formRepeat:{
                     number:'',
                     name:'',
                     gender: '',
                     codepass:'',
                     code:'',
                     telephone:'',
                     email:'',
                },
                 form2: {
                    fileName: '',
                    versionFile: ''
                },
                rules2: {
                    versionFile: [
                        { required: true, message: '请上传文件', trigger: 'blur' }
					]
                },
                 rules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    number: [
                        { required: true, message: '请输入工号', trigger: 'blur' }
                    ],
                    role: [
                        { required: true, message: '请输入角色', trigger: 'blur' }
                    ],
                    // telephone: [
                    //     { required: true, message: '请输入联系方式', trigger: 'blur' },
                    //     { required: true, validator: validPhone, trigger: 'blur' }
                    // ],
                    // email: [
                    //     { required: true, message: '请输入邮箱', trigger: 'blur' },
                    //     { required: true, validator: validateEmail, trigger: 'blur' }
					// ],
                    code: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
						{ required: true, validator: validatePass, trigger: 'blur' }
					],
					codepass: [
                        { required: true, message: '请输入确认密码', trigger: 'blur' },
						{ required: true, validator: validatePass2, trigger: 'blur' }
                    ]
                },
                rules3: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    number: [
                        { required: true, message: '请输入工号', trigger: 'blur' }
                    ],
                    role: [
                        { required: true, message: '请输入角色', trigger: 'blur' }
                    ],
                    telephone: [
                        { required: true, message: '请输入联系方式', trigger: 'blur' },
                        { required: true, validator: validPhone, trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { required: true, validator: validateEmail, trigger: 'blur' }
					],
                },
                //新需求,管理员删除教师可以选择是否保留老师课程 
                dialogTips: false,
                flagExict: 2,
                //传递参数属性
                update:''

            }

        },
        created() {
            this.init()
        },
        methods: {
            init(){
                let self = this
                self.$http.get('/tes/user/page?pageNum='+self.currentPage+'&pageSize='+self.pagesize+'&identity='+1+'&userInfo='+self.Form.name).then(response => {
                    let res = response.data
                    if(res.code == '200'){
                         self.tableData = res.data.content
                         self.totalCount = res.data.total
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
             //关闭导入教师弹窗
            closeTeacherDialog(){
                this.$refs.form2.resetFields()
            },
            //修改信息
            repeatFn(id,name,userNumber,telephoneNumber,email,sexName){
               this.id=id
               this.dialog=true
               this.formRepeat.name=name
               this.formRepeat.number=userNumber
               this.formRepeat.telephone=telephoneNumber
               this.formRepeat.email=email
               this.formRepeat.gender=sexName
            },
            //初始化密码
            repeatCode(id){
                let self = this
                self.$http.put('/tes/user/'+id+'/init-password').then(response => {
                    let res = response.data
                    if(res.code == '200'){
                        self.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //修改提交
            submit(formRepeat){
                let self = this
                self.$refs[formRepeat].validate((valid) => {
                    if (valid) {
                        self.$http.put('/tes/user/'+self.id+'?identity=1',{
                           name:self.formRepeat.name,
                           userNumber:self.formRepeat.number,
                           telephoneNumber:self.formRepeat.telephone,
                           email:self.formRepeat.email,
                           sexName: self.formRepeat.gender,
                           //roleName:self.role
                        }).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '保存成功',
                                    type: 'success'
                                })
                                self.init()
                                self.dialog=false
                                this.$refs[formRepeat].resetFields()

                            }else{
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            //添加用户
            submitFn(formlist){
                let self = this
                self.$refs[formlist].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: '正在保存中...',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        })
                        self.$http.post('/tes/user?identity=1',{
                           name:self.formlist.name,
                           userNumber:self.formlist.number,
                           telephoneNumber:self.formlist.telephone,
                           email:self.formlist.email,
                           sexName: self.formlist.gender,
                           password:self.formlist.code,
                        }).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '保存成功',
                                    type: 'success'
                                })
                                self.init()
                                loading.close()
                                self.dialogVisible=false
                                self.$refs[formlist].resetFields()

                            }else{
                                self.$message.error(res.message)
                                loading.close()
                            }
                        }).catch(() => {
                             loading.close()
                        })
                    }
                })
            },
            //全选
			handleSelectionChange(val) {
				let valArr = []
				for(let i = 0; i < val.length; i++){
					valArr.push(val[i].id)
				}
				this.multipleSelection = valArr
            },
            //关闭弹窗
            closeDialog(){
                this.$nextTick(()=>{
                    this.$refs.formlist.resetFields()
                })
            },
            //搜索
            searchFn(){
                this.currentPage = 1
                this.init()
            },
            //添加
            addFn(){
                 this.dialogVisible=true
            },
            //批量导入
            listProp(){
                 this.form2.fileName = ''
                 this.form2.versionFile = ''
                 this.dialogFormVisibles=true
            },
             //保存
            dialogTipSave(){
                let self = this
                let url =''
                if(self.flagExict == 1){
                    url = '/tes/user/batch-delete?errorFlag='+ '' + '&updatePreseted=true'
                    self.update = true
                }else if(self.flagExict == 2){
                    url = '/tes/user/batch-delete?errorFlag='+ '' + '&updatePreseted='
                    self.update = ''
                }
                self.$http.post(url,self.multipleSelection).then((response) => {
                   let res = response.data;
                    if(res.code == '200'){
                        self.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        self.dialogTips = false
                        self.currentPage = 1
                        self.init()
                    }else if(res.code == '501'){
                        self.commonFn(self.multipleSelection,res.message)
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
             //删除方法
            commonFn(id,message){
                let self = this
                self.$confirm(''+message+',确定删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                self.$http.post('/tes/user/batch-delete?errorFlag=true'+'&updatePreseted='+self.update,self.multipleSelection) .then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        self.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        self.init()
                        self.dialogTips = false
                    }else{
                        self.$message.error(res.message)
                    }
                }).catch(() => {
                })
              })
            },
            //批量删除
            deleteFn(){
                let self = this;
				if(self.multipleSelection.length == 0){
                    self.$message({
                        message: '请选择要删除的内容',
                        type: 'warning'
                    })
					return
                }
				self.$confirm('是否删除选中?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// self.$http.post('/tes/user/batch-delete?errorFlag=',self.multipleSelection).then((response) => {
					// 	let res = response.data;
					// 	if(res.code == '200'){
                    //         self.$message({
                    //             message: '删除成功',
                    //             type: 'success'
                    //         })
                    //        // self.currentPage = 1
                    //         self.init()
					//     }else if(res.code == '501'){
                    //         self.commonFn(self.multipleSelection,res.message)

                    //     }else{
                    //         self.$message.error(res.message)
                    //     }
					// },(err) => {
					// 	console.log('err');
                    // })
                    self.dialogTips = true
				}).catch(() => {
				})

            },
             //分页
			handleSizeChange: function (size) {
				this.pagesize = size;
			},
			handleCurrentChange: function(currentPage) {
                this.currentPage = currentPage
                this.init()
            },

           //上传文件
            getFile($event) {
                let fileType = $event.target.files[0].name
                    fileType = fileType.substring((fileType.lastIndexOf('.') + 1), fileType.length)
                if(fileType.toLowerCase() != 'xls' && fileType.toLowerCase() != "xlsx"){
                    this.$message.error('请上传xls 或 xlsx格式的文件!')
                    return
                }
                this.form2.fileName = $event.target.files[0]
                this.form2.versionFile = $event.target.files[0].name
                $event.target.value=''
            },
            //上传文件确认
            saveForm(form2){
                let self = this
                if(self.form2.versionFile==''){
                    self.$message({
                        message: '请选择上传的文件',
                        type: 'warning'
                    })
					return
                }
                let formData = new FormData()
                formData.append('file', self.form2.fileName);
				self.$refs[form2].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: '文件导入中',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        })
                        self.$http.post('/tes/user/model/import', formData, {headers: {'Content-Type': 'multipart/form-data'}}).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                self.$message({
                                    message: '上传成功',
                                    type: 'success'
                                })
                                loading.close()
                                self.init()
                                $('#version-files').val('')
                                self.dialogFormVisibles = false
                                self.$refs[form2].resetFields()
                            }
                            else{
                                loading.close()
                                self.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            //关闭弹窗
            closeTeacher(){
                this.dialogFormVisibles = false
                $('#version-files').val('')
            },
        }
    }
</script>
<style scoped>
.el-form>>>.el-form-item__content{
    text-align: center
}
.el-form-item>>>.el-input__inner{
    width: 200px;
    line-height: 32px
}
.el-form-item>label{
    text-align: right
}
#version-files{
    position: absolute;
    left: 0;
    opacity: 0;
    height: 32px;
    top: 0px;
}
.el-form-item{
    width: 100%;
}
.dialogTips{
    margin: 10px auto;
    text-align: center;
}
.el-form--inline>>>.el-form-item__label {
    text-align: right;
    float: left;
    display: inline-block;
    width: 100px !important;
}
.el-form >>>.el-input__inner{
     width: 200px;
}
.flagExict{
    margin-top: 10px;
}
</style>
<style lang="scss" scoped>
 @import "./../../../styles/layout/color_variables";
  #Teach {
    width: $width;
    margin: 20px auto;
    color: #727272;
      .topcoumt{
       overflow: hidden;
        .el-input .el-input__inner{
            width: 200px;
        }
    }
    .btn-box{
        .button-style{
            margin-right: 10px;
        }
    }
}

</style>
